#include "browser.h"
#include "ui_browser.h"
#include"common.h"
#include <QtGui>
#include <QtNetwork>
#include <QtWebKit>
browser::browser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::browser)
{
    initUI();
    initVarList();
    initConnection();
}

browser::~browser()
{
    delete ui;
    killTimer(m_titleId);
}

void browser::initUI()
{
    ui->setupUi(this);
    ui->loadprogressBar->setValue(0);
    ui->loadprogressBar->setRange(0,100);
}

void browser::initVarList()
{
    QNetworkProxyFactory::setUseSystemConfiguration(true);// Use the network accessManager Proxy OK
    m_progress = 0;
    m_titleId = startTimer(1000);
}

void browser::initConnection()
{
    connect(ui->webView, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(ui->urllineEdit, SIGNAL(returnPressed()), SLOT(on_searchbutton_clicked()));
}



void browser::changeTitle()
{
    QTime tm = QTime::currentTime();
    QString time = tm.toString("hh:mm:ss");
    QString title = "myBrowser__" + time;
    this->setWindowTitle(title);
}

QString browser::getTitle()
{
    //
}
void browser::changeUrl(const QString &urlStr)
{
    ui->urllineEdit->setText(urlStr);
}

QString browser::getUrl()
{
    return ui->urllineEdit->text();
}

void browser::loadUrl(const QUrl &url)
{
    if(url.isValid())
    {
        ui->webView->load(url);
    }
}

QUrl browser::urlFromString(const QString &strUrl)
{
    return QUrl(strUrl);
}

QString browser::urlToString(const QUrl &url)
{
    return url.toString();
}

void browser::on_searchbutton_clicked()
{
    QString urlstr = ui->urllineEdit->text();
    loadUrl(urlFromString(urlstr));
}


void browser::setProgress(int p)
{
    m_progress = p;
    ui->loadprogressBar->setValue(p);
}

void browser::timerEvent(QTimerEvent *)
{
    changeTitle();
}

void browser::on_homepagepushButton_clicked()
{
    changeUrl(g_homePage);
    loadUrl(urlFromString(g_homePage));
}

